package com.hnkywl.sts.service.jggl;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.hnkywl.sts.dao.base.SjzdzDao;
import com.hnkywl.sts.dao.jggl.*;
import com.hnkywl.sts.dao.organ.CkDao;
import com.hnkywl.sts.dao.organ.QyjgDao;
import com.hnkywl.sts.dao.sys.GgDao;
import com.hnkywl.sts.dao.xsgl.KhDao;
import com.hnkywl.sts.entity.jggl.*;
import com.hnkywl.sts.entity.xsgl.Kh;
import com.hnkywl.sts.service.base.WebserviceTransService;
import com.hnkywl.sts.service.sys.YgService;
import net.ruixin.orm.hibernate.Page;
import org.apache.commons.lang3.StringUtils;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by Melody on 14-3-12.
 */
@Service
public class JgdService {
    private WebserviceTransService webserviceTransService;
    private JgdDao jgdDao;
    private JgdmxDao jgdmxDao;
    private JghjgdmxDao jghjgdmxDao;
    private KhDao khDao;
    private GgDao ggDao;
    private QyjgDao qyjgDao;
    private CkDao ckDao;
    private SjzdzDao sjzdzDao;
    private CkdDao ckdDao;
    private YqccmxDao yqccmxDao;

    @Transactional
    public String findJgdList(String jgdh, Date sqrqStart, Date sqrqEnd, Long sqgsId, Long sbgsId, Integer zt, int pageNo, int pageSize) throws ParseException {
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        Page jgdPage = this.jgdDao.findJgdList(jgdh, sqrqStart, sqrqEnd, sqgsId, sbgsId, zt, pageNo, pageSize);
        String jgdJson = gson.toJson(jgdPage.getResult());
        List<Map> sumList = this.jgdDao.findSumJgd(jgdh, sqrqStart, sqrqEnd, sqgsId, sbgsId, zt);
        Double jgzl = 0d;
        Double jghzl = 0d;
        if (sumList.size() != 0) {
            for (Map map : sumList) {
                jgzl += Double.valueOf((map.get("jgzl") == null ? 0d : map.get("jgzl")).toString());
                jghzl += Double.valueOf((map.get("jghzl") == null ? 0d : map.get("jghzl")).toString());
            }
            return "{\"total\":" + jgdPage.getTotalCount() + ",\"rows\":" + jgdJson + ",\"footer\":[{\"jgdh\":\"合计:\",\"jgzl\":" + jgzl + ",\"jghzl\":" + jghzl + "}]}";
        } else {
            return "{\"total\":" + jgdPage.getTotalCount() + ",\"rows\":" + jgdJson + "}";
        }
    }

    /**
     * 删除加工单
     *
     * @param id
     * @return
     */
    @Transactional
    public Jgd deleteJgd(Long id) {
        Jgd jgd = this.jgdDao.get(id);
        jgd.setDeleted(1);
        jgd.setLastUpdated(new Date());
        if (jgd.getJgdmxList() != null && jgd.getJgdmxList().size() != 0) {
            for (Jgdmx jgdmx : jgd.getJgdmxList()) {
                jgdmx.setDeleted(1);
                jgdmx.setLastUpdated(new Date());
                jgdmxDao.save(jgdmx);
            }
        }
        if (jgd.getJhgjgdmxList() != null && jgd.getJhgjgdmxList().size() != 0) {
            for (Jghjgdmx jghjgdmx : jgd.getJhgjgdmxList()) {
                jghjgdmx.setDeleted(1);
                jghjgdmx.setLastUpdated(new Date());
                jghjgdmxDao.save(jghjgdmx);
            }
        }
        this.jgdDao.save(jgd);
        this.jgdDao.deleteJgdmx(id);
        this.jgdDao.deleteJghjgdmx(id);
        return jgd;
    }

    /**
     * 审核状态
     *
     * @param id
     * @param status
     */
    @Transactional
    public void changeStatus(Long id, Integer status) {
        Jgd jgd = this.findJgdDetail(id);
        jgd.setZt(status);
        this.jgdDao.save(jgd);
    }

    /**
     * 查询加工单明细
     *
     * @param id
     * @return
     */
    @Transactional
    public Jgd findJgdDetail(Long id) {
        return this.jgdDao.get(id);
    }

    //加工调拨单生成json
    public String createJgdProcessToJson(Jgd jgd) {
        StringBuffer sb = new StringBuffer();
        sb.append("{\"materialProdNo\":\"").append(jgd.getJgdh()).append("\",");
        sb.append("\"rate\":\"").append(jgd.getRate()).append("\",");
        sb.append("\"customerNo\":\"").append(jgd.getSbgs().getBm()).append("\",\"items\":[");
        for (Jgdmx jgdmx : jgd.getJgdmxList()) {
            sb.append("{\"buyerCompany\":\"").append(jgd.getSbgs().getBm()).append("\",");
            sb.append("\"reportCompany\":\"").append(jgd.getSqgs().getBm()).append("\",");
            sb.append("\"warehouseCode\":\"").append(jgdmx.getKh().getCk().getBh()).append("\",");
            sb.append("\"warehouseName\":\"").append(jgdmx.getKh().getCk().getMc()).append("\",");
            sb.append("\"productCode\":\"").append(jgdmx.getJtwz().getPmCode()).append("\",");
            sb.append("\"productName\":\"").append(jgdmx.getJtwz().getName()).append("\",");
            sb.append("\"specCode\":\"").append(jgdmx.getJtwz().getGgCode()).append("\",");
            sb.append("\"specName\":\"").append(jgdmx.getJtwz().getGgxh()).append("\",");
            sb.append("\"materialCode\":\"").append(jgdmx.getJtwz().getCzCode()).append("\",");
            sb.append("\"materialName\":\"").append(jgdmx.getJtwz().getCz()).append("\",");
            sb.append("\"orginCode\":\"").append(jgdmx.getKh().getCd().getBm()).append("\",");
            sb.append("\"orginName\":\"").append(jgdmx.getKh().getCd().getZ()).append("\",");
            sb.append("\"numberUnit\":\"").append(jgdmx.getJtwz().getSldw()).append("\",");
            sb.append("\"number\":\"").append(jgdmx.getSbsl() == null ? 1 : jgdmx.getSbsl()).append("\",");
            sb.append("\"weightUnit\":\"").append(jgdmx.getJtwz().getDw()).append("\",");
            sb.append("\"weight\":\"").append(jgdmx.getSbzl()).append("\",");
            sb.append("\"sku\":\"").append(jgdmx.getKh().getSku()).append("\"},");
        }
        sb = sb.delete(sb.length() - 1, sb.length());
        sb.append("]}");
        // 调用接口
        String result = null;
        return result;
    }

    public Jgd findByJgdh(String jgdh) {
        return this.jgdDao.findUniqueByProperty("jgdh", jgdh);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public void createByKh(Kh kh, Jgd jgd, String number, String sku, String warehouseBillNo) {
        List<Jgdmx> jgdmxList = jgd.getJgdmxList();
        Jgdmx jgdmx = new Jgdmx();
        jgdmx.setKh(kh);
        jgdmx.setCd(kh.getCd());
        jgdmx.setCk(kh.getCk());
        jgdmx.setSbsl(Double.valueOf(number));
        jgdmx.setSbzl(kh.getSl());
        jgdmx.setJg_sbsl(Double.valueOf(number));
        jgdmx.setJg_sbzl(kh.getSl());
        jgdmx.setJtwz(kh.getJtwz());
        jgdmx.setJgd(jgd);
        jgdmx.setSku(sku);
        jgdmx.setZt("1");
        jgdmx.setCcNO(warehouseBillNo);
        jgdmx.setSfcx(false);
        jgdmxList.add(jgdmx);
        jgdDao.save(jgd);
    }

    // 保存加工单
    @Transactional
    public Jgd addJgd(JSONArray array) {
        Jgd jgd = new Jgd();
        DateFormat format = new SimpleDateFormat("yyyyMMddhhmmssSSSS");
        String jgdh = "JGDH" + "-" + format.format(new Date());
        jgd.setJgdh(jgdh);
        jgd.setJgrq(new Date());
        jgd.setSbgs(YgService.getCurrentYg().getZggs());
        jgd.setSbr(YgService.getCurrentYg());
        jgd.setCreateUser(YgService.getCurrentYg());
        jgd.setCreateOrgan(YgService.getCurrentYg().getZggs());
        jgd.setCreateDepartment(YgService.getCurrentYg().getZgjg());
        jgd.setSbrq(new Date());
        jgd.setZt(0);
        String sqgsId = "";
        List<Jgdmx> jgdmxList = new ArrayList<Jgdmx>();
        for (int i = 0; i < array.length(); i++) {
            Jgdmx jgdmx = new Jgdmx();
            JSONObject obj = null;
            try {
                obj = array.getJSONObject(i);
                jgdmx.setKh(khDao.get(Long.valueOf(obj.get("id").toString())));
                jgdmx.setJtwz(ggDao.get(Long.valueOf(obj.get("jtwz_id").toString())));
                jgdmx.setSbsl(Double.valueOf(obj.get("js").toString()));
                jgdmx.setSbzl(Double.valueOf(obj.get("kkdsl").toString()));
                jgdmx.setCk(ckDao.get(Long.valueOf(obj.get("ck_id").toString())));
                jgdmx.setCd(sjzdzDao.get(Long.valueOf(obj.get("cd_id").toString())));
                jgdmx.setCreateUser(YgService.getCurrentYg());
                jgdmx.setCreateOrgan(YgService.getCurrentYg().getZggs());
                jgdmx.setCreateDepartment(YgService.getCurrentYg().getZgjg());
                //  jz 可能为空
                try {
                    if (null != obj.get("jz") && StringUtils.isNotBlank(obj.get("jz").toString())) {
                        jgdmx.setJz(Double.valueOf(obj.get("jz").toString()));
                    }
                } catch (JSONException e) {
                    e.getMessage();
                }
                //  sku 可能为空
                try {
                    if (null != obj.get("sku") && StringUtils.isNotBlank(obj.get("sku").toString())) {
                        jgdmx.setSku(obj.get("sku").toString());
                    }
                } catch (JSONException e) {
                    e.getMessage();
                }
                jgdmx.setDateCreated(new Date());
                jgdmx.setDeleted(0);
                jgdmx.setZt("0");
                sqgsId = obj.get("sbgs_id").toString();
                jgdmxList.add(jgdmx);
            } catch (JSONException e) {
                e.printStackTrace();
                return null;
            }
        }
        jgd.setSqgs(qyjgDao.get(Long.valueOf(sqgsId)));
        jgd.setJgdmxList(jgdmxList);
        jgdDao.save(jgd);
        return jgd;
    }

    @Transactional
    public Jgd findById(Long jgdId) {
        return jgdDao.get(jgdId);
    }

    //  查看，加工单明细
    @Transactional
    public String findJgdmxDetail(String mxzt, Long jgdId, int pageNo, int pageSize) {
        Gson gson = new Gson();
        Page<Map> jgdmxPage = this.jgdDao.findJgdmxDetailList(mxzt, jgdId, pageNo, pageSize);
        Map sumJgdmx = jgdDao.findJgdHj(mxzt, jgdId);
        String json = gson.toJson(jgdmxPage.getResult());
        return "{\"total\":" + jgdmxPage.getTotalCount() + ",\"rows\":" + json + ",\"footer\":[{\"cd.z\":\"合计:\",\"sbsl\":" + sumJgdmx.get("sbsl") + ",\"sbzl\":" + sumJgdmx.get("sbzl") + ",\"jg_sbsl\":" + sumJgdmx.get("jg_sbsl") + ",\"jg_sbzl\":" + sumJgdmx.get("jg_sbzl") + "}]}";
    }

    /**
     * 加工调入冲销明细
     */
    @Transactional
    public String findJgdmxDrCxDetail(String jgdh, String khbm, Integer sftzd, int pageNo, int pageSize) {
        Gson gson = new Gson();
        Page<Map> jgdmxPage = this.jgdDao.findJgdmxDrCxList(jgdh, khbm, sftzd, pageNo, pageSize);
        Map sumJgdmx = jgdDao.findJgdDrCxHj(jgdh, khbm, sftzd);
        String json = gson.toJson(jgdmxPage.getResult());
        return "{\"total\":" + jgdmxPage.getTotalCount() + ",\"rows\":" + json + ",\"footer\":[{\"cd.z\":\"合计:\",\"sbsl\":" + sumJgdmx.get("sbsl") + ",\"sbzl\":" + sumJgdmx.get("sbzl") + ",\"jg_sbsl\":" + sumJgdmx.get("jg_sbsl") + ",\"jg_sbzl\":" + sumJgdmx.get("jg_sbzl") + "}]}";
    }

    // 修改，加工单明细
    public String findJgdmxContent(Long jgdId) {
        Gson gson = new Gson();
        List<Map> jgdmx = this.jgdDao.findJgdmxContentList(jgdId);
        Map sumJgdmx = jgdDao.findJgdHj("0", jgdId);
        String json = gson.toJson(jgdmx);
        return "{\"rows\":" + json + ",\"footer\":[{\"cd.z\":\"合计:\",\"sbsl\":" + sumJgdmx.get("sbsl") + ",\"sbzl\":" + sumJgdmx.get("sbzl") + "}]}";
    }

    @Transactional
    public void update(Jgd jgd) {
        jgdDao.save(jgd);
    }

    @Transactional
    public Jgd updateJgd(JSONArray array, JSONArray array1, String rate, String bz) {
        Long jgd_id = 0L;
        for (int i = 0; i < array.length(); i++) {
            JSONObject obj = null;
            try {
                obj = array.getJSONObject(i);
                Jgdmx jgdmx = this.jgdmxDao.get(Long.valueOf(obj.get("id").toString()));
                jgd_id = Long.valueOf(obj.get("jgd_id").toString());
                jgdmx.setSbsl(Double.valueOf(obj.get("sbsl").toString()));
                jgdmx.setSbzl(Double.valueOf(obj.get("sbzl").toString()));
                jgdmx.setLastUpdated(new Date());
                this.jgdmxDao.save(jgdmx);
            } catch (JSONException e) {
                e.printStackTrace();
                return null;
            }
        }
        Jgd jgd = jgdDao.get(jgd_id);

        if (null != array1) {
            String sql = " delete from t_biz_yqccmx y where  y.jgd_id =? ";
            this.yqccmxDao.executeSQL(sql, jgd_id);
            for (int i = 0; i < array1.length(); i++) {
                JSONObject obj1 = null;
                try {
                    obj1 = array1.getJSONObject(i);
                    Yqccmx yqccmx = new Yqccmx();
                    yqccmx.setJgd(jgd);
                    yqccmx.setJtwz(ggDao.get(Long.valueOf(obj1.get("wzggId").toString())));
                    yqccmx.setCd(sjzdzDao.get(Long.valueOf(obj1.get("cdId").toString())));
                    yqccmx.setCcsl(Double.valueOf(obj1.get("ccsl").toString().toString()));
                    yqccmx.setCczl(Double.valueOf(obj1.get("cczl").toString().toString()));
                    yqccmx.setLastUpdated(new Date());
                    yqccmx.setCreateUser(YgService.getCurrentYg());
                    yqccmx.setCreateOrgan(YgService.getCurrentYg().getZggs());
                    yqccmx.setCreateDepartment(YgService.getCurrentYg().getZgjg());
                    yqccmx.setDateCreated(new Date());
                    this.yqccmxDao.save(yqccmx);
                } catch (JSONException e) {
                    e.printStackTrace();
                    return null;
                }
            }
        }


        if (null != jgd) {
            if (StringUtils.isNotEmpty(rate)) {
                jgd.setRate(rate);
            }
            if (StringUtils.isNotEmpty(bz)) {
                jgd.setBz(bz);
            }
            this.jgdDao.save(jgd);
        }
        return jgd;
    }

    @Transactional
    public String findCkdDetail(Long jgdmx_id, int pageNo, int pageSize) {
        Gson gson = new Gson();
        Page<Map> ckdMxPage = this.jgdDao.findCkdDetail(jgdmx_id, pageNo, pageSize);
        Map sumCkdmx = jgdDao.findCkdHj(jgdmx_id);
        String json = gson.toJson(ckdMxPage.getResult());
        return "{\"total\":" + ckdMxPage.getTotalCount() + ",\"rows\":" + json + ",\"footer\":[{\"cd\":\"合计:\",\"jgsl\":" + sumCkdmx.get("jg_sbsl") + ",\"jgzl\":" + sumCkdmx.get("jg_sbzl") + "}]}";
    }

    @Transactional
    public String findCkdcxList(String ckdh, String khbm, Integer sftzd, String cxdh, int pageNo, int pageSize) {
        Gson gson = new Gson();
        Page<Map> ckdcxPage = this.jgdDao.findCkdcxList(ckdh, khbm, sftzd, cxdh, pageNo, pageSize);
        Map sumCkdcx = jgdDao.findCkdcxHj(ckdh, khbm, sftzd, cxdh);
        String json = gson.toJson(ckdcxPage.getResult());
        return "{\"total\":" + ckdcxPage.getTotalCount() + ",\"rows\":" + json + ",\"footer\":[{\"cd\":\"合计:\",\"jgsl\":" + sumCkdcx.get("jgsl") + ",\"jgzl\":" + sumCkdcx.get("jgzl") + "}]}";
    }


    @Transactional
    public Jgdmx findJgdmxById(Long jgdmx_id) {
        return jgdmxDao.get(jgdmx_id);
    }

    @Transactional
    public void handJgdDrCxKh(Kh kh) throws RuntimeException {
        //判断是否已经出库
        if (!kh.getCshsl().equals(kh.getSl())) {
            throw new RuntimeException("货物已经出库，无法冲销！");
        }
        kh.setSl(0d);
        kh.setKkdsl(0d);
        kh.setJs(0);
        khDao.save(kh);
    }

    @Transactional
    public void saveJgdmx(Jgdmx jgdmx, Long ckdId) {
        // 更新加工单明细，数量和重量
        jgdmxDao.save(jgdmx);
        // 更新出库单是否调整单为真
        String sql = "update t_biz_ckd t set t.sftzd = 1 where t.id = ?";
        this.jgdmxDao.executeSQL(sql, ckdId);
        // 更新原来的出库单为已冲销单
        Ckd ckd = this.ckdDao.get(ckdId);
        String hql = "from Ckd where warehousebillno=? and jgdmx.id =? and ckd_tz = 0";
        Ckd yckd = (Ckd) this.ckdDao.find(hql, ckd.getWarehousebillno(), ckd.getJgdmx().getId()).get(0);
        yckd.setCkd_tz(2);
        this.ckdDao.save(yckd);
    }

    @Transactional
    public Long findJgdmxIdByContion(Long ckId, Long jgtzId, String warehouseBillNo) {
        List list = this.jgdDao.findJgdmxIdByContion(ckId, jgtzId, warehouseBillNo);
        if (null != list && list.size() > 0) {
            Map map = (Map) list.get(0);
            if (null != map && null != map.get("jgdmxId") && StringUtils.isNotBlank(map.get("jgdmxId").toString())) {
                return Long.parseLong(map.get("jgdmxId").toString());
            }
        }
        return null;
    }

    @Transactional
    public void saveJgdmx(Jgdmx jgdmx) {
        this.jgdmxDao.save(jgdmx);
    }

    @Transactional
    public void cxJgdmx(Jgdmx jgdmx) {
        Jgdmx jgdmxSave = new Jgdmx();
        jgdmxSave.setJgd(jgdmx.getJgd());
        jgdmxSave.setKh(jgdmx.getKh());
        jgdmxSave.setCd(jgdmx.getCd());
        jgdmxSave.setCk(jgdmx.getCk());
        jgdmxSave.setSbsl(jgdmx.getSbsl());
        jgdmxSave.setSbzl(jgdmx.getSbzl());
        jgdmxSave.setJg_sbsl(jgdmx.getJg_sbsl() - 2 * jgdmx.getJg_sbsl());
        jgdmxSave.setJg_sbzl(jgdmx.getJg_sbzl() - 2 * jgdmx.getJg_sbzl());
        jgdmxSave.setJtwz(jgdmx.getJtwz());
        jgdmxSave.setSku(jgdmx.getSku());
        jgdmxSave.setZt("1");
        jgdmxSave.setCcNO(jgdmx.getCcNO());
        jgdmxSave.setSfcx(true);
        jgdmxDao.save(jgdmxSave);
    }

    public String findJgglYqccmx(Long jgdId) {
        Gson gson = new Gson();
        List<Map> jgdmx = this.jgdDao.findJgglYqccmx(jgdId);
        String json = gson.toJson(jgdmx);
        return "{\"rows\":" + json + "}";
    }


    public String jgddetail_yqccmx(Long jgdId, int pageNo, int pageSize) {
        Gson gson = new Gson();
        Page<Map> jgdYqccmxPage = this.jgdDao.findJgdYqccmxDetailList(jgdId, pageNo, pageSize);
        Map sumJgdYqccmx = jgdDao.findJgdYqccmxHj(jgdId);
        String json = gson.toJson(jgdYqccmxPage.getResult());
        return "{\"total\":" + jgdYqccmxPage.getTotalCount() + ",\"rows\":" + json + ",\"footer\":[{\"cd.z\":\"合计:\",\"ccsl\":" + sumJgdYqccmx.get("ccsl") + ",\"cczl\":" + sumJgdYqccmx.get("cczl") + "}]}";
    }

    @Autowired
    public void setJgdDao(JgdDao jgdDao) {
        this.jgdDao = jgdDao;
    }

    @Autowired
    public void setJgdmxDao(JgdmxDao jgdmxDao) {
        this.jgdmxDao = jgdmxDao;
    }

    @Autowired
    public void setJghjgdmxDao(JghjgdmxDao jghjgdmxDao) {
        this.jghjgdmxDao = jghjgdmxDao;
    }

    @Autowired
    public void setKhDao(KhDao khDao) {
        this.khDao = khDao;
    }

    @Autowired
    public void setGgDao(GgDao ggDao) {
        this.ggDao = ggDao;
    }

    @Autowired
    public void setQyjgDao(QyjgDao qyjgDao) {
        this.qyjgDao = qyjgDao;
    }

    @Autowired
    public void setCkDao(CkDao ckDao) {
        this.ckDao = ckDao;
    }

    @Autowired
    public void setSjzdzDao(SjzdzDao sjzdzDao) {
        this.sjzdzDao = sjzdzDao;
    }

    @Autowired
    public void setCkdDao(CkdDao ckdDao) {
        this.ckdDao = ckdDao;
    }

    @Autowired
    public void setWebserviceTransService(WebserviceTransService webserviceTransService) {
        this.webserviceTransService = webserviceTransService;
    }

    @Autowired
    public void setYqccmxDao(YqccmxDao yqccmxDao) {
        this.yqccmxDao = yqccmxDao;
    }

}
